package com.apiit.webserviceclient.utility;

import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Intent;
import android.widget.Toast;

import com.apiit.webserviceclient.Caller;
import com.apiit.webserviceclient.activities.MainActivity;

public class BPEL_Process {

	public static String result = "";
	AlertDialog	ad;

	public BPEL_Response doRequest(BPEL_Request request)
			throws InterruptedException {
		BPEL_Response response = new BPEL_Response();
		String soapRequest = "";

		soapRequest = request.getUrl() + "-=-=-";
		Map<String, String> xpathMap = request.getXpathMap();

		int temp1 = 0;
		for (Map.Entry<String, String> entry : xpathMap.entrySet()) {
			temp1++;
			if (temp1 == xpathMap.size()) {
				soapRequest = soapRequest + entry.getKey() + ":"
						+ entry.getValue();
			} else {
				soapRequest = soapRequest + entry.getKey() + ":"
						+ entry.getValue() + "===";
			}
		}

		soapRequest = soapRequest + "-=-=-";

		Map<String, String> parametersMap = request.getParametersMap();

		temp1 = 0;
		for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
			temp1++;
			if (temp1 == parametersMap.size()) {
				soapRequest = soapRequest + entry.getKey() + "="
						+ entry.getValue();
			} else {
				soapRequest = soapRequest + entry.getKey() + "="
						+ entry.getValue() + "&";
			}
		}

		soapRequest = soapRequest + "-=-=-";

		soapRequest = soapRequest + GlobalData.cookies;

		soapRequest = soapRequest + "-=-=-";

		soapRequest = soapRequest + request.getType();

		result = "START";
		Caller caller = new Caller();
		caller.parameters = soapRequest;
		caller.join();
		caller.start();

		while (result.equals("START")) {
			Thread.sleep(20);
		}

		String[] initialResultsArray = result.split("-=-=-");
		response.setCookies(initialResultsArray[1]);
		GlobalData.cookies = initialResultsArray[1];
		response.setStatus(initialResultsArray[2]);
		String[] resultsToDisplay = initialResultsArray[0].split("---");
		String[] resultsKeyVal;

		Map<String, String> resultsMap = new HashMap<String, String>();
		try {
			for (int i = 0; i < resultsToDisplay.length; i++) {
				resultsKeyVal = resultsToDisplay[i].split("===");
				resultsMap.put(resultsKeyVal[0], resultsKeyVal[1]);
			}

			response.setResultsMap(resultsMap);
		} catch (Exception e) {
			response.setStatus( "Error");
			//Toast.makeText(this, "Bookmark is Selected",
					//Toast.LENGTH_LONG).show();


		}
		return response;
	}
}
